package com.markyao.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.markyao.service.AuthService;
import com.markyao.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    AuthService authService;
    private final ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
        /*
        1.判断请求路径是否是controller方法(HandlerMethod)
        2.判断token是否为空
        3.验证token,loginService
        4.如果成功放行
         */
        String token = request.getHeader("Authorization");
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if(!StringUtils.hasText(token)){
            //写回提示未登录
            Result failed = Result.failed(-555, "未登录服务器.");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(objectMapper.writeValueAsString(failed));

            return false;
        }
        boolean f=authService.checkToken(token);
        if(!f){
            //写回提示未登录
            Result failed = Result.failed(-555, "未登录服务器.");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(objectMapper.writeValueAsString(failed));
            return false;
        }

        return true;

    }

}
